package com.yang.demo.model;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Map;

/**
 * HTTP响应包装类
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class HttpResponse<T> {

    /**
     * 响应状态码
     */
    private int statusCode;

    /**
     * 响应消息
     */
    private String message;

    /**
     * 响应头
     */
    private Map<String, String> headers;

    /**
     * 响应体（字符串形式）
     */
    private String body;

    /**
     * 响应体（解析后的对象）
     */
    private T data;

    /**
     * 响应时间（毫秒）
     */
    private long responseTime;

    /**
     * 是否成功
     */
    public boolean isSuccess() {
        return statusCode >= 200 && statusCode < 300;
    }

    /**
     * 是否客户端错误
     */
    public boolean isClientError() {
        return statusCode >= 400 && statusCode < 500;
    }

    /**
     * 是否服务器错误
     */
    public boolean isServerError() {
        return statusCode >= 500 && statusCode < 600;
    }

    /**
     * 获取指定响应头的值
     */
    public String getHeader(String name) {
        return headers != null ? headers.get(name) : null;
    }

    /**
     * 获取Content-Type
     */
    public String getContentType() {
        return getHeader("Content-Type");
    }

    /**
     * 是否为JSON响应
     */
    public boolean isJsonResponse() {
        String contentType = getContentType();
        return contentType != null && contentType.contains("application/json");
    }

    /**
     * 获取响应体长度
     */
    public int getContentLength() {
        String length = getHeader("Content-Length");
        if (length != null) {
            try {
                return Integer.parseInt(length);
            } catch (NumberFormatException e) {
                return -1;
            }
        }
        return body != null ? body.length() : 0;
    }

    @Override
    public String toString() {
        return "HttpResponse{" +
                "statusCode=" + statusCode +
                ", message='" + message + '\'' +
                ", headers=" + headers +
                ", body='" + (body != null && body.length() > 200 ? body.substring(0, 200) + "..." : body) + '\'' +
                ", data=" + data +
                ", responseTime=" + responseTime +
                '}';
    }
}